package com.lalilu.lread.ui.weight

import android.animation.ValueAnimator
import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.lalilu.lread.R
import com.lalilu.lread.databinding.DialogBookLoadingBinding
import com.lalilu.lread.utils.StatusBarUtil

class BookLoadingDialog private constructor() :
    DialogFragment(R.layout.dialog_book_loading),
    ValueAnimator.AnimatorUpdateListener {
    private var loadingResult = false

    override fun onAnimationUpdate(p0: ValueAnimator) {
        if (p0.animatedValue as Float in 0.55f..0.6f && loadingResult) {
            hideDialog()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return Dialog(requireContext(), R.style.BookLoadingDialog).also {
            it.window?.setWindowAnimations(R.style.BookLoadingDialog)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        StatusBarUtil.setStatusBarColorByWindow(dialog!!.window, requireActivity())
        DialogBookLoadingBinding.bind(view).animatorUpdateListener = this
    }

    override fun onStart() {
        super.onStart()
        val params = dialog?.window?.attributes ?: return
        params.width = MATCH_PARENT
        params.height = MATCH_PARENT
    }

    companion object {

        fun showDialog(manager: FragmentManager, tag: String) {
            getInstance().loadingResult = false
            getInstance().show(manager, tag)
        }

        fun postHideDialog() {
            getInstance().loadingResult = true
        }

        fun hideDialog() {
            val dialog = getInstance()
            if (!dialog.isHidden && dialog.isVisible) {
                getInstance().dismiss()
            }
        }

        @Volatile
        private var instance: BookLoadingDialog? = null

        fun getInstance(): BookLoadingDialog {
            instance ?: synchronized(BookLoadingDialog::class.java) {
                instance = instance ?: BookLoadingDialog()
            }
            return instance!!
        }
    }


}